package com.means.polymerize.assembly.filter;

import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.CharsetUtil;
import cn.hutool.extra.servlet.ServletUtil;

import javax.servlet.ReadListener;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;

/**
 * Request Body 缓存 Wrapper
 *
 * @author xuhaifneg
 * @date 2021.05.05
 */
public class CacheRequestBodyWrapper extends HttpServletRequestWrapper {
    /**
     * 缓存的内容
     */
    private static final ThreadLocal<byte[]> BODY = ThreadLocal.withInitial(() -> new byte[]{});

    public CacheRequestBodyWrapper(HttpServletRequest request) {
        super(request);
        BODY.set(ServletUtil.getBodyBytes(request));
    }

    @Override
    public BufferedReader getReader() {
        return IoUtil.toBuffered(IoUtil.getReader(this.getInputStream(), CharsetUtil.CHARSET_UTF_8));
    }

    @Override
    public ServletInputStream getInputStream() {
        final ByteArrayInputStream inputStream = IoUtil.toStream(BODY.get());
        return new ServletInputStream() {
            @Override
            public int read() {
                return inputStream.read();
            }

            @Override
            public boolean isFinished() {
                return true;
            }

            @Override
            public boolean isReady() {
                return true;
            }

            @Override
            public void setReadListener(ReadListener readListener) {
            }
        };
    }
}
